﻿#pragma once

// ref: https://blog.csdn.net/audi2/article/details/54410300
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <boost/iostreams/device/back_inserter.hpp>

#include <vector>
#include <sstream>
#include <iostream>

bool gzip_compress(std::vector<char>& in, std::vector<char>& out)
{
    try
    {
        using namespace boost::iostreams;
        filtering_ostream fos;    // 具有filter功能的输出流
        fos.push(gzip_compressor(gzip_params(gzip::best_compression)));  // gzip压缩功能
        fos.push(boost::iostreams::back_inserter(out));     // 输出流的数据的目的地
        fos.write((const char*)(in.data()), in.size());
        boost::iostreams::close(fos);  // flush. 此函数调用后,存储的是gzip压缩后的数据
    }
    catch (const std::exception& e)
    {
        std::cerr << "compress error: " << e.what();
        return false;
    }
    return true;
}

bool gzip_decompress(std::vector<char>& in, std::vector<char>& out)
{
    try
    {
        using namespace boost::iostreams;
        filtering_ostream fos;
        fos.push(gzip_decompressor());  // gzip解压缩功能
        fos.push(boost::iostreams::back_inserter(out)); // 存放流的数据的目的地
        fos.write((const char*)(in.data()), in.size()); // 把压缩的数据写入流
        boost::iostreams::close(fos); // flush. 
    }
    catch (const std::exception& e)
    {
        std::cerr << "compress error: " << e.what();
        return false;
    }
    return true;
}
